<template>
  <div class="hello">

    <el-row class="">
      <el-col :span="10">
        <div class="grid-content bg-purple1"> </div>
      </el-col>

      <el-col :span="4">
        <div class="buttongroupcon buttongroup">
          <el-input
            v-model="username"
            placeholder="用户名"
          >用户名</el-input>
          <el-input
            v-model="room"
            placeholder="房间号"
          >房间号</el-input>
          <el-button
            type="primary"
            :disabled="noconnect"
            v-on:click="clickconnect"
          >连接</el-button>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="10">
          <el-button
            type="primary"
            :disabled="!noconnect"
            v-on:click="sharedesk"
          >共享桌面</el-button>
      </el-col>
    </el-row>

    <el-row class="videobuttongroup">
      <!-- <el-button type="primary" v-on:click="start">获取本地设备</el-button>
    <el-button type="success" v-on:click="call">呼叫远端</el-button> -->
      <el-button
        type="danger"
        v-on:click="huangup"
      > 挂断</el-button>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="4">
        <div class="grid-content"></div>
      </el-col>
      <el-col :span="8">
        <div class="grid-content bg-purple">
          <video
            autoplay
            id="localst"
            playsinline
            muted
          ></video>
        </div>

        <el-input
          type="textarea"
          :rows="10"
          placeholder="本地sdp信息"
          v-model="localtextarea"
        >
        </el-input>
      </el-col>

      <el-col :span="8">
        <div class="grid-content bg-purple">
          <video
            autoplay
            id="remotest"
            playsinline
          ></video>
        </div>

        <el-input
          type="textarea"
          :rows="10"
          placeholder="远端sdp信息"
          v-model="remotetextarea"
        >
        </el-input>

      </el-col>

    </el-row>

  </div>
</template>
<script>
import * as io from "socket.io-client";
import adapter from "webrtc-adapter";

// alert("浏览器:" + getExplorerInfo().type + "\n 版本:" + getExplorerInfo().version);

export default {
  name: "skonetoone",
  data() {
    return {
      socket: Object,
      isconnect: false,
      content: "",
      msginput: "",
      room: "",
      username: "",
      localstsrc: Object,
      remotestrc: "",
      pc: Object,
      localtextarea: "",
      remotetextarea: "",
      status: "",
      room: "",
      username: "",
      noconnect: null,
      explorversion:"",
      explor:""
    };
  },
  methods: {
    clickconnect: function() {
      this.socket = io.connect();

      var room = this.room;
      // console.log("room id is :" +this.room)
      this.socket.on("joined", (room, id) => {
        this.status = "joined";

        this.noconnect = "disabled";
        this.isconnect = null;

        console.log(
          "joined!! room id is :" +
            room +
            "id is:" +
            id +
            "status:" +
            this.status
        );
      });

      this.socket.on("otherjoin", (room, id) => {
        console.log("otherjoin this room");
        this.status = "joined_conn";
        this.call();

        console.log(
          "otherjoin!! room id is :" +
            room +
            "id is:" +
            id +
            "status:" +
            this.status
        );
      });

      this.socket.on("leaved", (room, id) => {
        this.status = "leaved";
        this.isconnect = false;
        this.huangup();
        console.log(
          "leaved!! room id is :" +
            room +
            "id is:" +
            id +
            "status:" +
            this.status
        );
      });

      this.socket.on("full", (room, id) => {
        this.status = "full";
        this.socket.disconnect();
        console.log(
          "full!! room id is :" + room + "id is:" + id + "status:" + this.status
        );
        this.$alert("房间已满 退出", "HTML 片段", {
          dangerouslyUseHTMLString: true
        });
        this.huangup();
      });

      this.socket.on("message", data => {
        // this.content = this.content + data.user + ":" + data.data + "\r";
        // console.log(room)
        // console.log(data)
        // console.log(id)
        // console.log(this.content)
        if (data.type == "send") {
          let desc = data.data;

          switch (data.data.type) {
            case "offer":
              console.log("into answer offer");
              this.createpeerconnection();
              console.log("the offer desc is",desc);
              this.pc.setRemoteDescription(new RTCSessionDescription(desc));
	      this.remotetextarea = desc.sdp;
              this.pc
                .createAnswer()
                .then(desc => {
                  console.log("we have answer");
                  this.pc.setLocalDescription(desc);
		  this.localtextarea=desc.sdp;
                  this.sendMessage(this.room, desc);
                })
                .catch(err => {
                  console.error("Failed get anster");
                });
              break;
            case "answer":
              this.pc.setRemoteDescription(new RTCSessionDescription(desc));
              this.remotetextarea = desc.sdp;

              let senders = this.pc.getSenders();

              console.log("sender is", senders);
              console.log("into answer type ");
              break;
            case "candidate":

              
              // console.log(this.getExplorerInfo().version)
              console.log("into candidate type", data);
          if(this.explor=="Chrome" &&parseInt(this.explorversion)<70){
              var newcandidate={
                sdpMlineIndex: data.data.label,
                candidate: data.data.candidate,         
                sdpMid:data.data.label
              }
          }
          else{
            console.log("in to new chrome")
             var newcandidate={
                sdpMlineIndex: data.data.label,
                candidate: data.data.candidate,
                sdpMid:data.data.label
              }
          }
	  	
              console.log("into yang on candidate dat is:");
              console.log(newcandidate);


              let candidate = new RTCIceCandidate(newcandidate);
              this.pc.addIceCandidate(candidate);
              break;
            default:
              console.log("into default type");
              console.log(data.type);
              break;
          }
        }
      });

      this.socket.on("bye", data => {
        // this.content = this.content + data.user + ":" + data.data + "\r";
        this.status = "joined_unbind";
        console.log(
          "bye!! room id is :" + room + "id is:" + id + "status:" + this.status
        );
        this.closelocalmedia();
        // console.log(room)
        // console.log(data)
        // console.log(id)
        // console.log(this.content)
      });

      this.socket.emit("join", room, this.username);

      // alert(123)
    },
    getExplorerInfo: function() {
      var explorer = window.navigator.userAgent.toLowerCase();
      //ie
      if (explorer.indexOf("msie") >= 0) {
        var ver = explorer.match(/msie ([\d.]+)/)[1];
        return { type: "IE", version: ver };
      }
      //firefox
      else if (explorer.indexOf("firefox") >= 0) {
        var ver = explorer.match(/firefox\/([\d.]+)/)[1];
        return { type: "Firefox", version: ver };
      }
      //Chrome
      else if (explorer.indexOf("chrome") >= 0) {
        var ver = explorer.match(/chrome\/([\d.]+)/)[1];
        return { type: "Chrome", version: ver };
      }
      //Opera
      else if (explorer.indexOf("opera") >= 0) {
        var ver = explorer.match(/opera.([\d.]+)/)[1];
        return { type: "Opera", version: ver };
      }
      //Safari
      else if (explorer.indexOf("Safari") >= 0) {
        var ver = explorer.match(/version\/([\d.]+)/)[1];
        return { type: "Safari", version: ver };
      }
    },
    start: function() {
      // 确认是否支持webrtc
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        console.log("get user media not supported!");
        return;
      } else {
        //设置需要什么媒体数据 这里设置音频和视频
        let constraints = {
          video: true,
          audio: true
        };
        let that = this;
        //获取音频和视频的媒体流
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then(stream => {
            // 获取成功后触发回调 把媒体流写入准备好的video标签
            let localst = document.querySelector("#localst");
            localst.srcObject = stream;
            console.log(stream);
            this.localstsrc = stream;
          })
          .catch(err => {
            console.log("faild get usermedia stream", err.message);
            console.log(err.message);
            console.log(err.name);
            console.log(err.code);
            alert(err.code);
            alert(err.message);
            alert(err.name);
          });
      }

      console.log("start");
    },
    huangup: function() {
      if (this.pc) {
        this.pc.close();
        this.pc = null;
      }

      setTimeout(() => {
        window.location.reload();
      }, 2000);

      //  let localst=document.querySelector('#localst')
      //  localst.srcObject = null
      // this.pc1.close()
      // this.pc2.close()
      // this.pc1=null
      // this.pc2=null
      console.log("huangup");
    },
    closelocalmedia: function() {
      if (this.localstsrc && this.localstsrc.getTracks()) {
        this.localst.getTracks().forEach(track => {
          track.stop();
        });
      }
    },
    sendMessage: function(roomid, data) {
      console.log("send p2p message", roomid, data);
      if (this.socket) {
        this.socket.emit("message", roomid, data);
      }
    },
    call: function() {
      this.createpeerconnection();
      if (this.status == "joined_conn") {
        if (this.pc) {
          console.log("into calllll!!");
          var options = {
            offerToReceiveAudio: 1,
            offerToReceiveVideo: 1
          };

          this.pc
            .createOffer(options)
            .then(desc => {
              this.localtextarea = desc.sdp;
              this.pc.setLocalDescription(desc);

              this.sendMessage(this.room, desc);
            })
            .catch(err => {
              console.log;
            });
        }
      }
    },
    createpeerconnection: function() {
      console.log("create peerconnection!!");

      let pcConfig = {
        iceServers: [
          {
            urls: ["stun:122.114.71.215:3478"],
            username: "yang",
            credential: "123"
          },         
        ],
        // iceTransportPolicy:"relay"
      };
      console.log("in to peerconnection");
      //this.pc = new RTCPeerConnection();
      this.pc = new RTCPeerConnection(pcConfig);
      this.pc.onicecandidate = e => {
        // console.log("find an new candidate11111")
        if (e.candidate) {
          console.log("find an new candidate", e.candidate);
          console.log(e);
          if(e.address=="127.0.0.1"){
            return
          }
          console.log(this.explor)
           console.log(this.explorversion)
          if(this.explor=="Chrome" &&parseInt(this.explorversion)<70){
              var newcandidate={
                type: "candidate",
                label: e.candidate.sdpMLineIndex,
                id: e.candidate.sdpMid,  
                candidate: e.candidate.candidate          
              }
          }
          else{
            console.log("in to new chrome")
             var newcandidate={
                type: "candidate",
                label: e.candidate.sdpMLineIndex,
                id: e.candidate.sdpMid,
                candidate: e.candidate.candidate,
                sdpMid:e.candidate.sdpMLineIndex
              }
          }
          


          this.sendMessage(this.room,newcandidate );
          //
        }
      };
      this.pc.ontrack = e => {
        console.log("on track in get");
        let localst = document.querySelector("#remotest");
        console.log("track is", e);
        localst.srcObject = e.streams[0];
      };
      console.log("will in to localstsrc");

      console.log(this.localstsrc);
      console.log(this);
      //  console.log(this.pc)
      if (this.localstsrc) {
        console.log("localstsrc get tracks");
        this.localstsrc.getTracks().forEach(track => {
          console.log("get new tracks")
          console.log(this.pc)
          this.pc.addTrack(track,this.localstsrc);
        });
      }


    }
    ,
    sharedesk: function(){

    navigator.mediaDevices.getDisplayMedia({ audio: false, video: true })
                          .then(stream => {



                            let localst = document.querySelector("#localst");
                            localst.srcObject = stream;
                            console.log("i get share desk,",stream)
                            console.log(this.localstsrc.getTracks())
                            console.log("this is decks tracks",stream.getTracks())
                            let senders = this.pc.getSenders();
                            senders.forEach(sender => {
                              console.log(sender.track.kind)
                              if(sender.track.kind == "video"){
                                sender.replaceTrack(stream.getTracks()[0])
                              }
                            })
                          })
                          .catch(handleError);      
        }
  },
  created: function() {
    this.explor=this.getExplorerInfo().type
    this.explorversion= this.getExplorerInfo().version.substr(0,2)

    this.start();
  }
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  /* padding: 20px; */
  border-radius: 4px;
  min-height: 330px;
}
video {
  height: 300px;
  object-fit: fill;
}
.buttongroup {
  margin-top: 30px;
  margin-bottom: 20px;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.buttongroupcon {
  display: flex;
}
.videobuttongroup {
  margin-bottom: 10px;
}
</style>
